import { View, Picker } from "@tarojs/components";
import {
  AtSearchBar,
  AtTabs,
  AtTabsPane,
  AtList,
  AtListItem,
  AtActionSheet,
  AtActionSheetItem,
  AtMessage,
  AtPagination
} from "taro-ui";
import { useEffect, useState } from "react";

import "./index.scss";

import {
  getDetectListbyuserApi,
  getInspectbyuserApi,
  getWarnbyuserApi,
  removeDetectDataApi,
  removeInspectDataApi,
  getWarnConfirmApi
} from "../../utils/api";
import Taro, { useDidShow, useRouter } from "@tarojs/taro";

const selector = [
  {
    title: "全部",
    type: 0
  },
  {
    title: "未确认",
    type: 1
  },
  {
    title: "已确认",
    type: 2
  }
];

const detect_result = {
  1: "待完成",
  2: "正常",
  3: "蚁情",
  4: "入侵",
  5: "低电量",
  9: "其他"
};
const warnTypes = [
  {
    id: 0,
    title: "全部"
  },
  {
    id: 1,
    title: "未确认"
  },
  {
    id: 2,
    title: "已处理"
  },
  {
    id: 3,
    title: "误报"
  }
];

const pageSize = 10;

const Index = () => {
  const router = useRouter();
  const [value2, setValue2] = useState("");
  const [current, setCurrent] = useState(0);

  // 探测数据
  const [detectList, setDetectList] = useState([]);
  const [delectOpen, setDelectOpen] = useState(false);
  const [delectId, setDelectId] = useState("");
  const [detectTotal, setDetectTotal] = useState(0);
  const [detectCurrentPage, setDetectCurrentPage] = useState(1);
  const pageChange1 = e => {
    setDetectCurrentPage(e.current);
  };
  useEffect(() => {
    detectData();
  }, [detectCurrentPage, value2]);

  // 检查数据
  const [inspect, setInspect] = useState([]);
  const [inspectOpen, setInspectOpen] = useState(false);
  const [inspectId, setInspectId] = useState("");
  const [inspect_done, set_inspect_done] = useState(false);
  const [inspectTotal, setInspectTotal] = useState(0);
  const [inspectCurrentPage, setInspectCurrentPage] = useState(1);
  const [inspect_is_done, set_inspect_is_done] = useState(0);
  const pageChange2 = e => {
    setInspectCurrentPage(e.current);
  };
  useEffect(() => {
    inspectData();
  }, [inspectCurrentPage, value2, inspect_is_done]);
  // 报警数据
  const [warnList, setWarnList] = useState([]);
  const [warnOpen, setWarnOpen] = useState(false);
  const [warnId, setWarnId] = useState("");
  const [warnTotal, setWarnTotal] = useState(0);
  const [warnCurrentPage, setWarnCurrentPage] = useState(1);
  const [warn_confirm_res, set_warn_confirm_res] = useState(0);
  const pageChange3 = e => {
    setWarnCurrentPage(e.current);
  };
  useEffect(() => {
    warnData();
  }, [warnCurrentPage, value2, warn_confirm_res]);

  const [pickertitle, set_pickertitle] = useState("全部");
  const [pickertitle2, set_pickertitle2] = useState("全部");

  useDidShow(() => {
    if (router.params.tabs) {
      setCurrent(+router.params.tabs);
    } else {
      Taro.getStorage({
        key: "current",
        success: function(res) {
          setCurrent(+res.data);
        },
        fail: function() {
          setCurrent(0);
        }
      });
    }
    setCurrent(router.params.tabs ? +router.params.tabs : 0);
    detectData();
    inspectData();
    warnData();
  });

  const tabList = [{ title: "探测" }, { title: "检查" }, { title: "报警" }];

  const handleChange = value => {
    setValue2(value);
  };

  const handleClick = () => {};

  const tabsClick = value => {
    setCurrent(value);
    Taro.setStorage({
      key: "current",
      data: value
    });
  };

  // 获取探测数据
  const detectData = async () => {
    const res = await getDetectListbyuserApi({
      point_keyword: value2,
      warn_type: 0,
      get_count: pageSize,
      start_index: pageSize * (detectCurrentPage - 1)
    });
    if (res.res === 0) {
      setDetectTotal(res.total_count);
      setDetectList(res.records);
    } else {
      Taro.atMessage({
        message: res.msg,
        type: "warning"
      });
    }
  };

  const handleClear = () => {
    setValue2("");
  };

  // 去探测新增
  const gotodetectadd = () => {
    Taro.navigateTo({
      url: "/pages/packageb/detect_add/index"
    });
  };

  // 打开探测面板
  const openDelect = item => {
    setDelectOpen(true);
    setDelectId(item.detect_id);
  };

  // 关闭探测面板
  const delectClose = () => {
    setDelectOpen(false);
  };

  // 删除探测
  const removeDelect = async () => {
    const res = await removeDetectDataApi({
      detect_id: delectId
    });
    if (res.res === 0) {
      Taro.atMessage({
        message: "删除成功",
        type: "success"
      });
      setDelectOpen(false);
      detectData();
    } else {
      Taro.atMessage({
        message: res.msg,
        type: "warning"
      });
    }
  };

  // 去探测详情
  const gotodetail = () => {
    setDelectOpen(false);
    Taro.navigateTo({
      url: "/pages/packageb/detect_detail/index?id=" + delectId
    });
  };

  // 获取检查数据
  const inspectData = async () => {
    const res = await getInspectbyuserApi({
      point_keyword: value2,
      warn_type: 0,
      is_done: inspect_is_done,
      get_count: pageSize,
      start_index: pageSize * (inspectCurrentPage - 1)
    });
    if (res.res === 0) {
      setInspectTotal(res.total_count);
      setInspect(res.records);
    } else {
      Taro.atMessage({
        message: res.msg,
        type: "warning"
      });
    }
  };

  // 打开检查面板
  const openInspect = item => {
    setInspectOpen(true);
    if (item.done_timestamp) {
      set_inspect_done(true);
    } else {
      set_inspect_done(false);
    }
    setInspectId(item.inspect_id);
  };

  // 关闭检查面板
  const inspectClose = () => {
    setInspectOpen(false);
  };

  // 删除检查
  const removeinspect = async () => {
    const res = await removeInspectDataApi({
      inspect_id: inspectId
    });
    if (res.res === 0) {
      Taro.atMessage({
        message: "删除成功",
        type: "success"
      });
      setInspectOpen(false);
      inspectData();
    } else {
      Taro.atMessage({
        message: res.msg,
        type: "warning"
      });
    }
  };

  // 完成检查
  const gotodone = () => {
    setInspectOpen(false);
    Taro.navigateTo({
      url: "/pages/packageb/inspect_done/index?id=" + inspectId
    });
  };

  // 检查详情
  const gotodetail2 = () => {
    setInspectOpen(false);
    Taro.navigateTo({
      url: "/pages/packageb/inspect_detail/index?id=" + inspectId
    });
  };

  // 获取报警数据
  const warnData = async () => {
    const res = await getWarnbyuserApi({
      point_keyword: value2,
      confirm_res: warn_confirm_res,
      warn_type: 0,
      get_count: pageSize,
      start_index: pageSize * (warnCurrentPage - 1)
    });
    if (res.res === 0) {
      setWarnTotal(res.total_count);
      setWarnList(res.records);
    } else {
      Taro.atMessage({
        message: res.msg,
        type: "warning"
      });
    }
  };

  // 打开报警面板
  const openWarn = item => {
    // setWarnOpen(true);
    // setWarnId(item.warn_id);
    Taro.navigateTo({
      url: "/pages/packageb/warn_detail/index?id=" + item.warn_id
    });
  };

  // 关闭报警面板
  const warnClose = () => {
    setWarnOpen(false);
  };

  // 确认报警
  const confirmWarn = async () => {
    const res = await getWarnConfirmApi({
      warn_id: warnId,
      confirm_res: 3
    });
    if (res.res === 0) {
      Taro.atMessage({
        message: "确认成功",
        type: "success"
      });
      setWarnOpen(false);
      warnData();
    } else {
      Taro.atMessage({
        message: res.msg,
        type: "warning"
      });
    }
  };

  const rangeChange = e => {
    const val = e.detail.value;
    selector.forEach(item => {
      if (item.type == val) {
        set_pickertitle(item.title);
      }
    });
    set_inspect_is_done(e.detail.value);
  };

  const rangeChange2 = e => {
    const val = e.detail.value;
    // console.log(val);
    // warnTypes.forEach(item => {
    //   if (item.id == val) {
    //     set_pickertitle2(item.title);
    //   }
    // });
    set_pickertitle2(warnTypes[val].title);
    set_warn_confirm_res(warnTypes[val].id);
  };

  return (
    <View className="mine-wrap">
      <AtSearchBar
        value={value2}
        onChange={handleChange}
        onActionClick={handleClick}
        placeholder="布点名称关键字"
        onClear={handleClear}
      />
      {current === 1 && (
        <>
          <Picker
            mode="selector"
            range={selector}
            onChange={rangeChange}
            rangeKey="title"
          >
            <AtList>
              <AtListItem title="检查筛选" extraText={pickertitle} />
            </AtList>
          </Picker>
        </>
      )}
      {current === 2 && (
        <>
          <Picker
            mode="selector"
            range={warnTypes}
            onChange={rangeChange2}
            rangeKey="title"
          >
            <AtList>
              <AtListItem title="确认结果" extraText={pickertitle2} />
            </AtList>
          </Picker>
        </>
      )}

      <AtTabs current={current} tabList={tabList} onClick={tabsClick}>
        <AtTabsPane current={current} index={0} style={{ height: "100%" }}>
          <View>
            <View className="button-wrap">
              <View className="button-item">探测过滤</View>
              <View className="button-item" onClick={gotodetectadd}>
                新建探测
              </View>
            </View>
            <AtList>
              {detectList.map(item => {
                return (
                  <AtListItem
                    title={item.project_name + "-" + item.point_name}
                    arrow="right"
                    extraText={detect_result[item.warn_type]}
                    onClick={() => openDelect(item)}
                    className={item.warn_type == 1 ? "not0" : ""}
                  />
                );
              })}
            </AtList>
            <AtPagination
              total={detectTotal}
              pageSize={pageSize}
              current={detectCurrentPage}
              onPageChange={pageChange1}
            />
          </View>
        </AtTabsPane>
        <AtTabsPane current={current} index={1}>
          <View>
            <AtList>
              {inspect.map(item => {
                return (
                  <AtListItem
                    title={item.project_name + "-" + item.point_name}
                    arrow="right"
                    extraText={item.done_timestamp ? "已确认" : "未确认"}
                    onClick={() => openInspect(item)}
                  />
                );
              })}
            </AtList>
            <AtPagination
              total={inspectTotal}
              pageSize={pageSize}
              current={inspectCurrentPage}
              onPageChange={pageChange2}
            />
          </View>
        </AtTabsPane>
        <AtTabsPane current={current} index={2}>
          <View>
            <AtList>
              {warnList.map(item => {
                return (
                  <AtListItem
                    title={item.project_name + "-" + item.point_name}
                    arrow="right"
                    onClick={() => openWarn(item)}
                    extraText={detect_result[item.warn_type]}
                  />
                );
              })}
            </AtList>
            <AtPagination
              total={warnTotal}
              pageSize={pageSize}
              current={warnCurrentPage}
              onPageChange={pageChange3}
            />
          </View>
        </AtTabsPane>
      </AtTabs>

      {/* 探测面板 */}
      <AtActionSheet
        isOpened={delectOpen}
        cancelText="取消"
        onClose={delectClose}
        onCancel={delectClose}
      >
        <AtActionSheetItem onClick={gotodetail}>查看探测详情</AtActionSheetItem>
        <AtActionSheetItem onClick={removeDelect}>删除探测</AtActionSheetItem>
      </AtActionSheet>

      {/* 检查面板 */}
      <AtActionSheet
        isOpened={inspectOpen}
        cancelText="取消"
        onClose={inspectClose}
        onCancel={inspectClose}
      >
        <AtActionSheetItem onClick={gotodetail2}>
          查看检查详情
        </AtActionSheetItem>
        {!inspect_done && (
          <AtActionSheetItem onClick={gotodone}>完成检查</AtActionSheetItem>
        )}

        <AtActionSheetItem onClick={removeinspect}>删除检查</AtActionSheetItem>
      </AtActionSheet>

      {/* 报警面板 */}
      <AtActionSheet
        isOpened={warnOpen}
        cancelText="取消"
        onClose={warnClose}
        onCancel={warnClose}
      >
        <AtActionSheetItem onClick={confirmWarn}>确认</AtActionSheetItem>
      </AtActionSheet>
      <AtMessage />
    </View>
  );
};

export default Index;
